<?php


namespace App\Containers\AppSection\Questionnaire\SubActions;


use App\Containers\AppSection\Questionnaire\Tasks\CreateValueTask;
use App\Containers\AppSection\Questionnaire\Tasks\DeleteAllValuesByResponseIdTask;
use App\Containers\AppSection\Questionnaire\Tasks\FindFieldByIdTask;
use App\Ship\Parents\Actions\Action;
use Arr;

class UpdateResponseSubAction extends Action
{
    public function run($responseId, $values)
    {
        $newValues = [];
        //Разбиение на лица
        foreach ($values as $v) {
            if (empty($newValues[$v['person']]))
                $newValues[$v['person']] = [];
            $v['field'] = app(FindFieldByIdTask::class)->run($v['field_id']);
            array_push($newValues[$v['person']], $v);
        }
        ksort($newValues, SORT_NUMERIC);

        //Удаление всех значений
        app(DeleteAllValuesByResponseIdTask::class)->run($responseId);

        foreach ($newValues as $value) {
            usort($value, function ($a, $b): int {
                if ($a['field']['order'] == $b['field']['order']) {
                    return ($a['field']['id'] < $b['field']['id']) ? -1 : 1;
                }
                return ($a['field']['order'] < $b['field']['order']) ? -1 : 1;
            });

            foreach ($value as $v) {
                $v['response_id'] = $responseId;
                app(CreateValueTask::class)->run($v);
            }
        }
    }
}
